import Datastore from 'nedb-promises'

const DeleteData = (db: Datastore<{ _id: string; }>, queryParams: any, resJSON: ResponseDataType, callback: Function) => {
  db.find({ ...queryParams, _del: false }).then((res: any) => {
    let dataLen = res.length
    if (dataLen === 0 && queryParams.id) {
      resJSON.note = `id为 ${queryParams.id} 的记录不存在`
    } else {
      console.log('delete', queryParams)
      db.update(queryParams, { $set: { _del: true } }).then(async (res: any) => {
        resJSON = {
          code: res,
          note: '删除成功',
          data: [],
          total: res
        }
        callback && callback(resJSON)
      }).catch((error) => {
        resJSON.note = error
        callback && callback(resJSON)
      })
    }
  }).catch((error) => {
    resJSON.note = error
    callback && callback(resJSON)
  })
}

const DeleteDataSync = async (db: Datastore<{ _id: string; }>, queryParams: any, resJSON: ResponseDataType) => {
  await db.find({ ...queryParams, _del: false }).then(async (res: any) => {
    let dataLen = res.length
    if (dataLen === 0) {
      resJSON.note = `id为 ${queryParams.id} 的记录不存在`
    } else {
      await db.update(queryParams, { $set: { _del: true } }).then(async (res: any) => {
        resJSON = {
          code: queryParams.id,
          note: '删除成功',
          data: [],
          total: res
        }
      }).catch((error) => {
        resJSON.note = error
      })
    }
  }).catch((error) => {
    resJSON.note = error
  })
  return resJSON
}

export {
  DeleteData,
  DeleteDataSync,
}